#include "Trap.h"
#include "Game.h"
#include "ObjectDatabase.h"
#include "StringLib.h"
#include "Renderer.h"
#include "MeleeWeapon.h"
#include "Util.h"
#include "RandomObjectGenerator.h"
#include "Character.h"
#include "Tile.h"
#include "Level.h"

Trap::Trap(TrapType type, int numTriggers) : Obstacle(GT_OB_TRAP) {
	m_types[TH_TRAP_TYPE] = type;
	m_numTriggers = numTriggers;
	m_isVisible = false;
	m_blocking = false;
	const TrapInfo& info = g_objectDatabase->getTrapInfo(type);
}

Trap::Trap(std::ifstream& file) : Obstacle(GT_OB_TRAP, file) {
	int* tokens = Util::intSplit(file);
	m_types[TH_TRAP_TYPE] = tokens[0];
	m_numTriggers = tokens[0];
	m_isVisible = tokens[1] == 1;
	m_blocking = false;
	delete[] tokens;
}

Trap::~Trap() {
}

void Trap::save(std::ofstream& file) const {
	file << getType(TH_GENERIC_TYPE) << " " << getType(TH_TRAP_TYPE) << "\n";
	Obstacle::save(file);
	file << m_numTriggers << " " << (m_isVisible ? 1 : 0) << "\n";
}

void Trap::render(float x, float y) {
	g_renderer->render(*this, x, y);
}

void Trap::logDetails(TextLog& log) const {
	Obstacle::logDetails(log);
	log.addBlankLine();
	if(m_numTriggers == 0)
		g_textLog->addLine(g_stringLib->getTextString(ST_TRAP_EMPTY));
}

void Trap::trigger(Character* c) {
	m_isVisible = true;
	switch(getType(TH_TRAP_TYPE)) {
	case TT_DAGGER: {
		Weapon* dagger = RandomObjectGenerator::createMeleeWeapon(MWT_SHORT_SWORD, m_tile->getLevel()->getDLevel());
		if(x_in_y(10+dagger->getAccuracy(), c->getStat(NIM))) {
			int damage = std::max(0, dagger->getRandomDamage() - c->getStat(STR)/2);
			c->logTrap(TT_DAGGER, true, damage);
			c->dealDamage(damage);
		} else
			c->logTrap(TT_DAGGER, false);
		c->getTile()->addItem(dagger);
		break;
	}
	}
	m_numTriggers--;
}